﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XAct.Messages;
using ZH.Infrastructure.Dto.Request.Login;
using ZH.Infrastructure.Dto.Response;
using ZH.Infrastructure.Dto.Response.admin;
using ZH.Infrastructure.Tools;
using ZH.Service.Instance;
using ZH.Service.Interface;

namespace ZH.Api.Admin.Controllers.Cashier
{
    /// <summary>
    /// 收银端·登录
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CashierController : Controller
    {
        private readonly I_Cashier_Service _cashier_Service;
        private readonly IConfiguration _configuration;

        public CashierController(IConfiguration configuration, I_Cashier_Service cashier_Service)
        {


            _cashier_Service = cashier_Service;
            _configuration = configuration;

        }
        /// <summary>
        /// 收银员登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Logins(Login_Request_Dto dto)
        {
            dto.code = Config.GUID2();
            var result = await _cashier_Service.Logins(dto);
            if (result.code == Api_Code.ok)
            {

                var claims = new[]
                 {
                    new Claim(ClaimTypes.Name,  dto.code),
                    new Claim(ClaimTypes.Actor,dto.account!.Trim()),
                    new Claim(ClaimTypes.Role,"Cashier")
                };
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecurityKey"]));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                string jwtKey = _configuration["JWT:issuer"];
                var token = new JwtSecurityToken(
                    issuer: jwtKey,
                    audience: jwtKey,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(60 * 60 * 12),
                    signingCredentials: creds);

                result.data = new
                {
                    token = new JwtSecurityTokenHandler().WriteToken(token)
                };
            }
            return Ok(result);
        }


        /// <summary>
        /// 检查登录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "Cashier")] //检查登录
        public IActionResult Check_Login()
        {
            var user = this.Get_Current_Cashier();
            if (user == null)
            {
                return Unauthorized();//返回401
            }

            return Ok(new Api_Response_Dto
            {
                code = 0,
                message = "ok",
                data = user
            });
        }
        /// <summary>
        /// 获取当前登录的商户
        /// </summary>
        /// <returns></returns>
        private User_Response_Dto? Get_Current_Cashier()
        {
            var code = Response.HttpContext.User.Identity?.Name;

            return _cashier_Service.Check_Login(code, "");
        }

    }

}
